package com.ruoyi.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.finance.domain.FeeDistributor;
import com.ruoyi.finance.domain.WalmartProfitReport;
import com.ruoyi.finance.domain.WalmartProfitReportDetail;
import com.ruoyi.finance.mapper.WalmartProfitReportDetailMapper;
import com.ruoyi.finance.service.WalmartProfitReportDetailService;
import com.ruoyi.walmart.domain.shipments.dto.CostFreightPair;
import com.ruoyi.walmart.domain.shipments.dto.SkuGtinKey;
import com.ruoyi.walmart.domain.shipments.dto.SkuGtinQty;
import com.ruoyi.walmart.mapper.shipments.ShipmentStockMapper;
import com.ruoyi.walmart.service.shipments.ShipmentMatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WalmartProfitReportDetailServiceImpl extends ServiceImpl<WalmartProfitReportDetailMapper, WalmartProfitReportDetail> implements WalmartProfitReportDetailService {

    @Autowired
    private WalmartProfitReportDetailMapper walmartProfitReportDetailMapper;
    @Autowired
    private ShipmentMatchService shipmentMatchService;
    @Autowired
    private ShipmentStockMapper shipmentStockMapper;
    /**
     * 批量插入
     */
    @Override
    public int insertBatchReportDetail(List<WalmartProfitReportDetail> details) {
        return walmartProfitReportDetailMapper.insertBatchReportDetail(details);
    }

    /**
     * 解析明细数据，并关联主表的wprId
     */
    @Transactional
    public List<WalmartProfitReportDetail> parseDetails(List<String[]> records, WalmartProfitReport wpr) {
        Map<String, WalmartProfitReportDetail> skuDetailsMap = new HashMap<>();
        if (records.size() <= 3) {
            return new ArrayList<>();
        }

        // 构建表头索引
        String[] header = records.get(0);
        Map<String, Integer> headerIndex = new HashMap<>();
        for (int i = 0; i < header.length; i++) {
            headerIndex.put(header[i].trim(), i);
        }
        int skuIdx = headerIndex.get("Partner Item Id");
        int gtinIdx = headerIndex.get("Partner GTIN");
        int transTypeIdx = headerIndex.get("Transaction Type");
        int transDescIdx = headerIndex.get("Transaction Description");
        int amountTypeIdx = headerIndex.get("Amount Type");
        int amountIdx = headerIndex.get("Amount");
        int qtyIdx = headerIndex.get("Ship Qty");
        Integer commissionSaveIdx = headerIndex.get("Commission Saving");
        Integer originalCommIdx = headerIndex.get("Original Commission");

        // 明细从第4行开始
        for (int i = 3; i < records.size(); i++) {
            String[] row = records.get(i);
            if (row.length <= amountIdx) continue;

            String sku = row[skuIdx].trim();
            //查询查询关联本地商品的sku
            String localSku = shipmentStockMapper.getLocalSkuByItemSku(sku);
            if(localSku != null){
                sku = localSku;
            }
            String gtin = row[gtinIdx].trim();
            String transactionType = row[transTypeIdx];
            String transactionDesc = row[transDescIdx].replace("\"", "").trim();
            String amountType = row[amountTypeIdx].trim();
            BigDecimal amountValue = parseBigDecimal(row[amountIdx]);
            Integer qtyValue = 0; // 默认值为 0

            // 检查 qtyValue 是否为空或无效值
            if (row[qtyIdx] != null && !row[qtyIdx].isEmpty()) {
                try {
                    qtyValue = Integer.valueOf(row[qtyIdx]); // 尝试将值转换为 Integer
                } catch (NumberFormatException e) {
                    // 如果转换失败，默认保持 qtyValue 为 0
                    System.out.println("Invalid qty value: " + row[qtyIdx]);
                }
            }

            // 如果sku或者gtin为空，跳过当前处理
            if (sku.isEmpty() || gtin.isEmpty()) {
                continue;
            }
            String skuGtinKey = sku + "|" + gtin;
            WalmartProfitReportDetail detail = skuDetailsMap.getOrDefault(skuGtinKey, new WalmartProfitReportDetail());
            // 设置关联字段
            detail.setId(IdWorker.getId());
            detail.setWprId(wpr.getId());
            detail.setSku(sku);
            detail.setGtin(gtin);

            // 汇总数据：WFS 费用
            if ("WFS Fulfillment fee".equalsIgnoreCase(transactionDesc)) {
                detail.setWfsFulfillmentFee(
                        Optional.ofNullable(detail.getWfsFulfillmentFee()).orElse(BigDecimal.ZERO).add(amountValue)
                );
            } else if ("WFS Return Shipping fee".equalsIgnoreCase(transactionDesc)) {
                detail.setWfsReturnShippingFee(
                        Optional.ofNullable(detail.getWfsReturnShippingFee()).orElse(BigDecimal.ZERO).add(amountValue)
                );
            }
            // 销售和退款明细处理
            if ("Sale".equalsIgnoreCase(transactionType)) {
                switch (amountType) {
                    case "Product Price":
                        detail.setSalesProductPrice(
                                Optional.ofNullable(detail.getSalesProductPrice()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        // 先检查 qtyValue 是否有效
                        if (qtyValue != null && qtyValue > 0) {
                            detail.setQty(
                                    Optional.ofNullable(detail.getQty()).orElse(0) + qtyValue
                            );
                        }
                        break;
                    case "Promo Code":
                        // Promo Code 只加价格，不加数量
                        detail.setSalesProductPrice(
                                Optional.ofNullable(detail.getSalesProductPrice()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                    case "Other tax (Fees)":
                        detail.setSalesOtherTaxesFee(
                                Optional.ofNullable(detail.getSalesOtherTaxesFee()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                    case "Product tax withheld":
                        detail.setSalesTaxWithheld(
                                Optional.ofNullable(detail.getSalesTaxWithheld()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                    case "Product tax":
                        detail.setSalesTax(
                                Optional.ofNullable(detail.getSalesTax()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                    case "Total Walmart Funded Savings":
                        detail.setSalesFundedSavings(
                                Optional.ofNullable(detail.getSalesFundedSavings()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                }

                if (commissionSaveIdx != null && commissionSaveIdx < row.length) {
                    detail.setSalesCommissionSavings(
                            Optional.ofNullable(detail.getSalesCommissionSavings()).orElse(BigDecimal.ZERO).add(parseBigDecimal(row[commissionSaveIdx]))
                    );
                }
                if (originalCommIdx != null && originalCommIdx < row.length) {
                    detail.setSalesCommission(
                            Optional.ofNullable(detail.getSalesCommission()).orElse(BigDecimal.ZERO).add(parseBigDecimal(row[originalCommIdx]))
                    );
                }

            } else if ("Refund".equalsIgnoreCase(transactionType)) {
                // 验证desc是否在有效范围内
                if (!VALID_REFUND_AMOUNT_TYPE.contains(amountType)) {
                    throw new IllegalArgumentException(
                            String.format("数据解析错误: '%s' 不在预期的金额类型范围内，请联系管理人员核查", amountType)
                    );
                }

                switch (amountType) {
                    case "Product Price":
                    case "Other tax (Fees)":
                        detail.setRefundProductPrice(
                                Optional.ofNullable(detail.getRefundProductPrice()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        // 先检查 qtyValue 是否有效
                        if (qtyValue != null && qtyValue > 0) {  // 或者 qtyValue != 0, 根据需要调整条件
                            detail.setRefundQty(
                                    Optional.ofNullable(detail.getRefundQty()).orElse(0) + qtyValue
                            );
                        }
                        break;
                    case "Commission on Product":
                        detail.setRefundCommission(
                                Optional.ofNullable(detail.getRefundCommission()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                    case "Total Walmart Funded Savings":
                    case "ExcessRefundAdjustment":
                        detail.setRefundFundedSavings(
                                Optional.ofNullable(detail.getRefundFundedSavings()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                    case "Product tax":
                        detail.setRefundTax(
                                Optional.ofNullable(detail.getRefundTax()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                    case "Product tax withheld":
                        detail.setRefundTaxWithheld(
                                Optional.ofNullable(detail.getRefundTaxWithheld()).orElse(BigDecimal.ZERO).add(amountValue)
                        );
                        break;
                }
            }
            skuDetailsMap.put(skuGtinKey, detail);  // 更新 Map
        }
        List<WalmartProfitReportDetail> details = new ArrayList<>(skuDetailsMap.values());

        // ✨ 集成分摊逻辑：按销售额比例分配 semTotal 到 detail.sem 字段
        BigDecimal semFeeTotal = wpr.getSemFeeTotal();
        if (semFeeTotal != null && semFeeTotal.compareTo(BigDecimal.ZERO) != 0) {
            FeeDistributor.distributeWithCompensation(
                    details,
                    wpr.getSemFeeTotal(),
                    WalmartProfitReportDetail::getSalesProductPrice, // 占比依据
                    WalmartProfitReportDetail::getSem,               // 获取目标值（用于补差）
                    WalmartProfitReportDetail::setSem,               // 设置目标值
                    2,                      // 保留两位小数
                    new BigDecimal("0.01"), // 误差允许值
                    false                   //是否需要修正方向
            );
        }

        // ✨ 其他的费用集成分摊逻辑：按销售额比例分配 setOtherFee 到 detail.ohterFee 字段
        BigDecimal otherFeeTotal = wpr.getOtherFeeTotal();
        if (otherFeeTotal != null && otherFeeTotal.compareTo(BigDecimal.ZERO) != 0) {
            FeeDistributor.distributeWithCompensation(
                    details,
                    wpr.getOtherFeeTotal(),
                    WalmartProfitReportDetail::getSalesProductPrice, // 占比依据
                    WalmartProfitReportDetail::getOtherFee,          // 获取目标值（用于补差）
                    WalmartProfitReportDetail::setOtherFee,          // 设置目标值
                    2,                      // 保留两位小数
                    new BigDecimal("0.01"), // 误差允许值
                    false                   //是否需要修正方向
            );
        }


        // 直接从 details 创建 SkuGtinQty 列表
        List<SkuGtinQty> skuGtinQtyList = details.stream()
                .filter(d -> d.getQty() != null && d.getQty() > 0)
                .collect(Collectors.groupingBy(
                        d -> new SkuGtinKey(d.getSku(), d.getGtin()),
                        Collectors.summingInt(WalmartProfitReportDetail::getQty)
                ))
                .entrySet().stream()
                .map(entry -> new SkuGtinQty(
                        entry.getKey().getSku(),
                        entry.getKey().getGtin(),
                        entry.getValue()
                ))
                .collect(Collectors.toList());

        // 调用修改后的方法
        Map<SkuGtinKey, CostFreightPair> costFreightMap =
                shipmentMatchService.allocateBillingQtyBySku(skuGtinQtyList, wpr.getAuthId(), wpr.getId());

        details = details.stream()
                .peek(detail -> {
                    SkuGtinKey key = new SkuGtinKey(detail.getSku(), detail.getGtin());
                    CostFreightPair pair = costFreightMap.get(key);
                    if (pair != null) {
                        detail.setProductCost(pair.getProductCost());
                        detail.setFirstLeg(pair.getFirstLeg());
                    } else {
                        // 如果没有找到对应的成本，可能需要按SKU查找
                        // 或者记录日志
                        System.out.println("未找到 SKU: " + detail.getSku() + ", GTIN: " + detail.getGtin() + " 的成本信息");
                    }
                })
                .collect(Collectors.toList());

        return details;
    }

    private BigDecimal parseBigDecimal(String str) {
        try {
            return new BigDecimal(str.trim());
        } catch (Exception e) {
            return BigDecimal.ZERO;

        }
    }
    // 定义有效的金额类型白名单
    private static final Set<String> VALID_REFUND_AMOUNT_TYPE = new HashSet<>(Arrays.asList(
            "Product Price",
            "Commission on Product",
            "Total Walmart Funded Savings",
            "Product tax",
            "Product tax withheld",
            "ExcessRefundAdjustment",
            "Other tax (Fees)"
    ));
}
